<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/17
 * Time: 下午2:01
 */

namespace app\common\model;

use think\Cache;
use think\Db;
use app\admin\model\Wallet;
use think\Exception;

//token加密密钥
define("H_TOKEN_SECRET", "SecretForShangJiYinApp");

class User extends Common
{

    /**
     * 判断用户是否存在
     *
     * @param string $account 待查询用户的ID或手机号
     * @return array|null 若用户存在则返回用户数组，否则返回null
     */
    static public function exists($account)
    {
        $user = Db::name("user")
            ->where("id|mobile", "=", $account)
            ->find();
        return $user;
    }

    /**
     *  注册用户
     * @param $nick_name
     * @param $mobile
     * @param $password
     * @param $confirm_password
     * @param int $parent_mobile
     * @param string $headimg
     * @return int|string
     * @throws ServerException
     * @throws UserException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function register($nick_name, $mobile, $password, $confirm_password, $parent_mobile = 0, $headimg = '', $brand_id = '')
    {
        //检测用户是否已存在
        if (self::exists($mobile)) {
            throw new UserException("手机号" . $mobile . "已被注册使用！");
        }
        if ($password != $confirm_password) {
            throw new UserException("两次密码不一样！");
        }

        if (!empty($parent_mobile)) {
            $parent = self::exists($parent_mobile);
            if (empty($parent)) {
                throw new UserException("没有此推荐人！");
            }
            $parent_id = $parent['id'];
            $parent_id2 = $parent['parent_id'];
        } else {
            $parent_id = 0;
            $parent_id2 = 0;
        }

        $nick_name = remove_all_tags($nick_name);
        if (empty($nick_name)) {
            throw new  UserException('请正确输入昵称，避免空格等特殊字符！');
        }

        //用户信息
        $user = array(
            'mobile' => $mobile,
            'parent_id' => $parent_id,
            'parent_id2' => $parent_id2,
            'nick_name' => $nick_name,
            'password' => encrypt_user_password($password),
            'create_time' => now_datetime(),
            'update_time' => now_datetime(),
            'brand_id' => $brand_id
        );

//        if(!empty($unionid)){
//            $find = Db::name('user')
//                ->where('unionid',$unionid)
//                ->find();
//            if($find){
//                throw new UserException('微信号已绑定，请勿重复绑定');
//            }
//            $user['unionid'] = $unionid;
//        }
//        if(!empty($openid)){
//            $user['openid'] = $openid;
//        }

        if (!empty($headimg)) {
            $headimg = str_replace('https://', 'http://', $headimg);
            $user['avatar'] = $headimg;
        }

        //创建用户
        $result = Db::name("user")->insertGetId($user);

        if (empty($result)) {
            throw new ServerException("创建新用户失败！数据库" . __FILE__ . __LINE__);
        }
        //返回用户uid
        return $result;
    }


    /**
     * 登录用户
     *
     * @param $mobile
     * @param $password
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws UserException
     */
    static public function login($mobile, $password, $captcha, $type)
    {
        if (empty($password) && empty($captcha)) {
            throw new UserException("请填写密码或者验证码！");
        }
        //查找用户
        $user = self::exists($mobile);

        //判断用户存在性
        if (!$user) {
            throw new UserException("用户【" . $mobile . "】不存在！");
        }

        /*密码登录*/
        if (!empty($password)) {
            //判断密码是否正确
            if (encrypt_user_password($password) != $user["password"]) {
                throw new UserException("登录密码错误！");
            }
        }

        if (!empty($captcha)) {
            //判断验证码是否正确
            Jhsms::verifyCaptcha($mobile, $captcha, $type);
        }

        //判断是否被拉黑
        if ($user["in_blacklist"]) {
            throw new UserException("您的账号已被拉黑，请及时联系管理员处理！");
        }
        if (empty($user["brand_id"])) {
//            throw new Exception("抱歉，游客暂不能登录商城");
        }

        /*添加登录时间,登录次数*/
        $last_time = date("Y-m-d", $user['last_login_time']);
        $now_time = date("Y-m-d");
        $arr['last_login_time'] = time();
        if ($now_time > $last_time) {
            $arr['login_days'] = $user['login_days'] + 1;
        }
        Db::name('user')
            ->where('id', $user['id'])
            ->update($arr);

        //返回token
        return array(
            "uid" => $user["id"],
        );
    }


    /**
     * 修改密码
     *
     * @param string $user 用户
     * @param string $oldpassword 旧密码
     * @param string $newpassword 新密码
     * @param string $confirmpassword 确认密码
     * @throws UserException
     */
    static public function changePassword($user, $oldpassword, $newpassword, $confirmpassword)
    {

        //判断旧密码对不对
        if (encrypt_user_password($oldpassword) != $user["password"]) {
            throw new UserException("旧密码错误！");
        }

        //新密码与确认密码是否一致
        if ($confirmpassword != $newpassword) {
            throw new UserException("新密码与确认密码不一致！");
        }

        //新密码是否未改变
        if ($oldpassword == $newpassword) {
            throw new UserException("新密码不能与旧密码相同！");
        }

        //修改密码
        $result = Db::name("user")
            ->where("id", $user["id"])
            ->setField("password", encrypt_user_password($newpassword));
        if ($result) {
        } else {
            throw new ServerException('密码未能保存');
        }
        return '新密码设置成功！';
    }

    /**
     * 忘记密码重新设置密码
     * @param String $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $confirmpassword 确认密码密码
     * @throws UserException
     */

    static public function forgetPassword($mobile, $newpassword, $confirmpassword)
    {
        //判断用户是否存在
        $user = User::exists($mobile);

        //判断确认密码是否相同
        if ($newpassword != $confirmpassword) {
            throw new UserException("请重新填写确认密码!");
        }
        //判断用户存在性
        if (!$user) {
            throw new UserException("手机号【" . $mobile . "】未注册！");
        }

        $oldpassword = $user['password'];
        if ($oldpassword == encrypt_user_password($newpassword)) {
            throw new UserException("新密码不能与旧密码一致！");
        }
        //修改密码
        $result = Db::name("user")
            ->where("id", $user["id"])
            ->setField("password", encrypt_user_password($newpassword));

        if ($result) {
        } else {
            throw new ServerException('密码未能保存');
        }
        return '新密码设置成功！';
    }

    /**
     * 获取默认地址
     */
    public static function getDefaultAddress($user_id)
    {
        $address = \db("user_address")->where("uid", $user_id)->where("is_def", 1)->find();
        if (!empty($address)) {
            $address["procity"] = self::getProCity($address);
        }
        return empty($address) ? [] : $address;
    }

    /**
     * 获取收获地址列表
     */
    public static function getAddressList($user_id)
    {
        $list = \db("user_address")->where("uid", $user_id)->select();
        foreach ($list as &$item) {
            $item["procity"] = self::getProCity($item);
        }
        return $list;
    }

    public static function getProCity($item)
    {
        return \db("region")->where("id_path", "1-" . $item['pro_id'] . "-" . $item["city_id"] . "-" . $item["area_id"])->value("name_path");
    }


    /**
     * 减少用户积分
     */
    public static function decScore($user_id, $score, $type, $order_id = 0)
    {
        //添加积分变动记录
        if ($type == 1) {
            self::modifyScore($user_id, $score, $type, "取消订单返还", $order_id);
            \db("user")->where("id", $user_id)->setInc("score", $score);
        } elseif ($type == 2) {
            self::modifyScore($user_id, $score, $type, "消费抵扣", $order_id);
            \db("user")->where("id", $user_id)->setDec("score", $score);
        }
    }

    /**
     * 积分变动记录
     */
    public static function modifyScore($user_id, $score, $type, $content, $order_id = 0)
    {
        $data = [
            "uid" => $user_id,
            "type" => $type,
            "score" => $score,
            "content" => $content,
            "order_id" => $order_id,
            "create_time" => time()
        ];
        \db("score_log")->insert($data);
    }



    //TODO

    /**
     * 修改用户头像
     *
     * @param array $user 用户
     * @param string $avatar 待修改的头像
     * @throws DeveloperException
     * @throws UserException
     */
    static public function modifyAvatar($user, $avatar)
    {
        //更新用户头像
        Db::name("user")
            ->where("id", $user["id"])
            ->setField("avatar", $avatar);
    }

    /**
     * 删除会员
     *
     * @param string $userId 待删除的会员ID
     * @param bool $isTotal 如果为true，则彻底删除数据；否则，添加删除字段
     */
    static public function remove($userId, $isTotal = false)
    {
        //修改关系链
        {
            //上级ID
            $parentId = Db::name("user")
                ->where("id", $userId)
                ->where("is_valid", 1)
                ->value("parent_id");

            //将所有下级拉取到上级
            Db::name("user")
                ->where("parent_id", $userId)
                ->where("is_valid", 1)
                ->setField("parent_id", $parentId);
        }

        //删除会员
        if ($isTotal) {
            Db::name("user")
                ->where("id", $userId)
                ->delete();
        } else {
            Db::name("user")
                ->where("id", $userId)
                ->setField("is_valid", 0);
        }
    }

    /**
     * 修改用户昵称
     * @param array $user 用户
     * @param $type 修改类型（1：昵称）
     * @param $content
     * @throws UserException
     * @internal param string $nickname 昵称
     */
    static public function setUpdate($user, $type, $content)
    {
        $content = remove_all_tags($content);

        if ($type == 1) {
            if (empty($content)) {
                throw new UserException('请正确输入昵称，避免空格和特殊字符！');
            }
            //更新用户昵称
            Db::name("user")
                ->where("id", $user["id"])
                ->setField("nick_name", $content);

            $str = '昵称修改成功！';
        } else {
            throw new ServerException('无此修改类型');
        }
        return $str;
    }

    /**
     * 意见反馈
     *
     * @param array $user 用户
     * @param string $content 反馈内容
     * @throws DeveloperException
     */
    static public function memberSuggest($user, $content)
    {
        $data = array(
            "uid" => $user["id"],
            "suggestion" => $content,
            "create_time" => now_datetime()
        );

        $res = Db::name("suggestion")->insert($data);
        if (!$res) {
            throw new DeveloperException('操作失败！');
        }
    }

    /**
     * 会员设置
     * @param $user
     * @return array
     */
    static public function userSet($user)
    {
        //头像
        $avatar = $user['avatar'];

        if (empty($avatar)) {
            $avatar = get_def_avatar();
        }

        //荣誉等级
        $level_img = Db::name('level')->where('id', $user['level'])->value('img_url');

        $arr = [
            'avatar' => $avatar,
            'nick_name' => $user['nick_name'],
            'level_img' => $level_img
        ];
        return $arr;
    }

    /**
     * 退出登录
     * @param $user_id
     * @return string
     */
    static public function userLogout($user_id)
    {
        $tokenName = "access_token-" . $user_id;
        Cache::store('redis')->rm($tokenName);
        return '退出登录成功！';
    }
}